from . import api
from .. import db
from .authentication import auth
from ..utils.aliyunVideo import *
from ..utils.checkUpload import *
from ..models import *
from flask import request, jsonify, g, current_app
import traceback, time, random

# √
# 随机查看匿名墙 概览
@api.route('/anonymousWallRandom', methods=['GET'])
def get_anonymous_wall_random():
    count = anonymousWall.query.count()
    if count == 0:
        response= jsonify(error='No select data!')
        response.status_code = 404
        return response

    rand = random.randrange(0, count) 
    anonymous_wall = anonymousWall.query.all()[rand]
    anonymous_wall = anonymous_wall.to_json()
    
    u_anonymous_wall_like = anonymousWallLike.query.filter(anonymousWallLike.user_id==g.current_user.user_id,
                                                            anonymousWallLike.anonymous_wall_id==anonymous_wall['anonymous_wall_id']).first()
    # print(u_anonymous_wall_like)

    anonymous_wall['is_user_like'] = True if u_anonymous_wall_like else False

    response = jsonify(message='Get love post data successfully!', anonymous_wall=anonymous_wall)
    response.status_code = 200
    return response

# √
# 发布匿名墙
@api.route('/anonymousWall', methods=['POST'])
def publish_anonymous_wall():
    # 生成anonymousWall对象，并插入到表中
    anonymous_wall = anonymousWall.from_json(request.json)
    
    try:
        db.session.add(anonymous_wall)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
        response = jsonify(error='Upload anonymous wall failed!', detail=traceback.format_exc())
        response.status_code = 400
        return response
        
    print('[+] add anonymous wall: %s' % anonymous_wall)
    response = jsonify(message='Upload anonymous wall successfully!')
    response.status_code = 200
    return response

# √
# 发布匿名墙评论
@api.route('/anonymousWallComment', methods=['POST'])
def publish_anonymous_wall_comment():
    # print('[+] add love comment: %s' % request.json)
    anonymous_wall_comment = anonymousWallComment.from_json(request.json)
    try:
        db.session.add(anonymous_wall_comment)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
        response = jsonify(error='Upload anonymous wall comment failed!', detail=traceback.format_exc())
        response.status_code = 403
        return response

    print('[+] Add anonymous wall comment: %r' % anonymous_wall_comment.anonymous_wall_id)
    response = jsonify(message='Upload anonymous wall comment successfully!')
    response.status_code = 200
    return response

# √
# 增加匿名墙喜欢
@api.route('/anonymousWallLike/<anonymous_wall_id>', methods=['POST'])
def add_anonymous_wall_like(anonymous_wall_id):
    anonymous_wall_like = anonymousWallLike(user_id=g.current_user.user_id, anonymous_wall_id=anonymous_wall_id)
    try:
        db.session.add(anonymous_wall_like)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
        response = jsonify(error="Add like successfully failed!", detail=traceback.format_exc())
        response.status_code = 403
        return response
        
    print('[+] Add anonymous wall: %r like' % anonymous_wall_like.anonymous_wall_id)
    response = jsonify(message='Add like successfully!')
    response.status_code = 200
    return response

# √
# 减少匿名墙喜欢
@api.route('/anonymousWallLike/<anonymous_wall_id>', methods=['DELETE'])
def del_anonymous_wall_like(anonymous_wall_id):
    anonymous_wall_like = anonymousWallLike.query.filter(anonymousWallLike.user_id==g.current_user.user_id, \
                                                            anonymousWallLike.anonymous_wall_id==anonymous_wall_id).first_or_404()
    try:
        db.session.delete(anonymous_wall_like)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
        response = jsonify(error="Delete like failed!", detail=traceback.format_exc())
        response.status_code = 403
        return response

    print('[-] Delete anonymous wall: %r like' % anonymous_wall_like.anonymous_wall_id)
    response = jsonify(message='Delete like successfully!')
    response.status_code = 200
    return response

# √
# 查看匿名墙详情
@api.route('/anonymousWallComment/<anonymous_wall_id>', methods=['GET'])
def get_anonymous_wall_detail(anonymous_wall_id):
    anonymous_wall = anonymousWall.query.get_or_404(anonymous_wall_id)
    anonymous_wall_comment = anonymousWallComment.query.filter_by(anonymous_wall_id=anonymous_wall_id).order_by(anonymousWallComment.publish_time).all()
    anonymous_wall_like = anonymousWallLike.query.filter(anonymousWallLike.user_id==g.current_user.user_id, \
                                                        anonymousWallLike.anonymous_wall_id==anonymous_wall_id).first()

    anonymous_wall = anonymous_wall.to_json()
    anonymous_wall['is_user_like'] = True if anonymous_wall_like else False

    if len(anonymous_wall_comment) == 0:
        response= jsonify(
            error='No select data!', 
            anonymous_wall=anonymous_wall, 
            anonymous_wall_comment=[],
            anonymous_wall_comment_count=0
        )
        response.status_code = 200
        return response

    anonymous_wall_comment = [l.to_json() for l in anonymous_wall_comment]


    print('[*] Get anonymous wall detail')
    response = jsonify(
        message='Get anonymous wall detail successfully!', 
        anonymous_wall=anonymous_wall, 
        anonymous_wall_comment=anonymous_wall_comment
    )
    response.status_code = 200
    return response


# ---------以下功能不实现----------
# 查看我的匿名墙
@api.route('/myAnonymousWall', methods=['GET'])
def get_my_anonymous_wall():
    anonymous_wall = anonymousWall.query.filter_by(user_id=g.current_user.user_id).all()
    if len(anonymous_wall) == 0:
        response= jsonify(
            error='No select data!'
        )
        response.status_code = 404
        return response

    anonymous_wall = [l.to_json() for l in anonymous_wall]
    u_anonymous_wall_like = anonymousWallLike.query.filter_by(user_id=g.current_user.user_id).all()
    u_anonymous_wall_like = [l.anonymous_wall_id for l in u_anonymous_wall_like]
    # print(u_anonymous_wall_like)

    for wall in anonymous_wall:
        wall['is_user_like'] = True if wall['anonymous_wall_id'] in u_anonymous_wall_like else False

    response = jsonify(message='Get love post data successfully!', anonymous_wall=anonymous_wall)
    response.status_code = 200
    return response


# 删除我的匿名墙
@api.route('/myAnonymousWall/<anonymous_wall_id>', methods=['DELETE'])
def del_my_anonymous_wall(anonymous_wall_id):
    anonymous_wall = anonymousWall.query.filter(anonymousWall.user_id==g.current_user.user_id, \
                                                            anonymousWall.anonymous_wall_id==anonymous_wall_id).first_or_404()
    try:
        db.session.delete(anonymous_wall)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
        response = jsonify(error="Delete anonymous wall failed!", detail=traceback.format_exc())
        response.status_code = 403
        return response

    print('[-] Delete anonymous wall: %r' % anonymous_wall.anonymous_wall_id)
    response = jsonify(message='Delete anonymous wall successfully!')
    response.status_code = 200
    return response
